import { LocalStorageVar } from '@/utils/localStorage'
import { customRef } from 'vue'

export function useLocalStorageRef<D>(value: D, localStorageId: string) {
  const localStorageVar = new LocalStorageVar<D>(value, localStorageId)
  localStorageVar.init()
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return localStorageVar.data
      },
      set(newValue) {
        if (newValue === undefined) {
          localStorageVar.clear()
        } else {
          localStorageVar.set(newValue)
        }
        trigger()
      },
    }
  })
}
